package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultList;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.base.utils.EntityUtil;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 岗位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/stepBrief")
public class StepBriefController extends BaseController {


    private static final long serialVersionUID = -3875859985981472887L;

    @Autowired
    private CommonConfigService commonConfigService;
    @Autowired
    private ProcessBriefService processBriefService;
    @Autowired
    private StepBriefService stepBriefService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private GroupService groupService;

    private static final EntityConfig entityConfig  = new EntityConfig();
    /**
     * 新建页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model, String parentId, String keyId) {
        ProcessBrief processBrief = null;
        StepBrief stepBrief = null;
        Set<String> fieldNames = Sets.newHashSet();
        if (StringUtils.isNotEmpty(parentId)){
            processBrief = processBriefService.get(parentId);
            stepBrief = new StepBrief();
            stepBrief.setProcessBrief(processBrief);
        }
        if (StringUtils.isNotEmpty(keyId)){
            stepBrief = stepBriefService.get(keyId);
        }
        try {
            Class table =  Class.forName(stepBrief.getProcessBrief().getTableKey());
            String[] allField =  EntityUtil.getFiledName(table);
            for(String field:allField){
                if(field.startsWith("duty") == true){
                    fieldNames.add(field);
                }
            }
            // LogUtil.info("fieldNames:"+ fieldNames);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("parentId", parentId);
        model.addAttribute("processBrief", processBrief);
        model.addAttribute("stepBrief", stepBrief);
        model.addAttribute("fieldNames", fieldNames);
        return "/main/company/stepBrief_input";
    }



    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String parentId,  String commonConfigId, String allmans, String keyId,
                       String departId, String groupId, String powerId, String postId, String variableName, String stepName,
                       int stepNo, String backStepNo,  String jointlySing, int routeType, int nextStepNo,
                       @RequestParam(required = false, value = "actionType") List<String> actionType,
                       @RequestParam(required = false, value = "specialType") List<String> specialType) {
        Map<String,Object> rMap=new HashMap<String,Object>();
        StepBrief stepBrief = null;
        ProcessBrief processBrief = null;
        CommonConfig commonConfig = null;
        if(StringUtils.isNotEmpty(keyId)){
            stepBrief = stepBriefService.get(keyId);
        }else{
            stepBrief = new StepBrief();
            stepBrief.setCreater(user);
        }
        if(StringUtils.isNotEmpty(parentId)){
            processBrief = processBriefService.get(parentId);
            stepBrief.setProcessBrief(processBrief);
        }
        if(StringUtils.isNotEmpty(commonConfigId)){
            commonConfig = commonConfigService.get(commonConfigId);
        }else{
            commonConfig = new CommonConfig();
        }
        if(StringUtils.equals(allmans, "1")){
            commonConfig.setAllmans(true);
        }else{
            commonConfig.setAllmans(false);
        }
        commonConfig.setDepartmentSet(getDepartSpit(departId));
        commonConfig.setGroupSet(getGroupSpit(groupId));
        commonConfig.setPowerSet(getPowerSpit(powerId));
        commonConfig.setPostSet(getPostSpit(postId));
        commonConfig.setVariable(variableName);
        if(StringUtils.isNotEmpty(commonConfigId)){
            commonConfigService.update(commonConfig);
        }else{
            commonConfigService.save(commonConfig);
        }
        stepBrief.setCommonConfig(commonConfig);
        stepBrief.setName(stepName);
        stepBrief.setStepNo(stepNo);
        if(StringUtils.isNotEmpty(backStepNo)){
            stepBrief.setBackStepNo(Integer.parseInt(backStepNo));
        }
        String strActionType = "";

        if(actionType != null && actionType.size()>0){
            for(String type:actionType){
                strActionType += type;
            }
        }
        stepBrief.setActionType(strActionType);
        if(StringUtils.equals(jointlySing, "1")){
            stepBrief.setJointlySing(true);
        }else{
            stepBrief.setJointlySing(false);
        }
        stepBrief.setRouteType(routeType);
        stepBrief.setNextStepNo(nextStepNo);
        String strSpecialType = "";

        if(specialType !=null && specialType.size()>0){
            for(String type:specialType){
                strSpecialType += type;
            }
        }
        stepBrief.setSpecialType(strSpecialType);
        stepBrief.setCompany(user.getCompany());
        if(StringUtils.isNotEmpty(keyId)){
            stepBriefService.update(stepBrief);
            rMap.put("message", "更新成功");
        }else{
            stepBriefService.save(stepBrief);
            rMap.put("message","保存成功");
        }
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 分割，部门id数组
     * @param str
     * @return
     */
    private Set<Department> getDepartSpit(String str) {
        Set<Department> departSet = new HashSet<Department>();
        if(StringUtils.isEmpty(str)) return departSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (StringUtils.isNotEmpty(item)) {
                departSet.add(departmentService.get(item));
            }
        }
        return departSet;
    }
    /**
     * 分割，岗位id数组
     * @param str
     * @return
     */
    private Set<Post> getPostSpit(String str) {
        Set<Post> postSet = new HashSet<Post>();
        if(StringUtils.isEmpty(str)) return postSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (StringUtils.isNotEmpty(item)) {
                postSet.add(postService.get(item));
            }
        }
        return postSet;
    }
    /**
     * 分割，群组id数组
     * @param str
     * @return
     */
    private Set<Group> getGroupSpit(String str) {
        Set<Group> groupSet = Sets.newHashSet();
        if(StringUtils.isEmpty(str)) return groupSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (StringUtils.isNotEmpty(item)) {
                groupSet.add(groupService.get(item));
            }
        }
        return groupSet;
    }
    /**
     * 分割，职权id数组
     * @param str
     * @return
     */
    private Set<Power> getPowerSpit(String str) {
        Set<Power> powerSet = Sets.newHashSet();
        if(StringUtils.isEmpty(str)) return powerSet;
        String[] ary = str.split(",");
        for (String item : ary) {
            if (StringUtils.isNotEmpty(item)) {
                powerSet.add(powerService.get(item));
            }
        }
        return powerSet;
    }


    /**
     * 操作
     */
    @RequestMapping(value = "delete/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String keyId) {
        if(StringUtils.isNotEmpty(keyId)){
            StepBrief stepBrief = stepBriefService.get(keyId);
            stepBrief.setState(BaseEnumManager.StateEnum.Delete);
            stepBriefService.update(stepBrief);
            return ajaxJson(resultService.successWithId(keyId));
        }else{
            return ajaxJson(resultService.fail());
        }
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters,String parentId) {
        Company company = user.getCompany();
        ProcessBrief processBrief = null;
        if (StringUtils.isNotEmpty(parentId)) {
            processBrief = processBriefService.get(parentId);
        }
        /*
        // 排序
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);*/
        SearchResultPaging searchResult = stepBriefService.pagingStepBrief(null,null,null, processBrief, company, BaseEnumManager.StateEnum.Enable);

        List<StepBrief> stepBriefList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(StepBrief stepBrief: stepBriefList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",stepBrief.getId());
            rMap.put("stepNo", stepBrief.getStepNo());
            rMap.put("name", stepBrief.getName());
            rMap.put("creater", stepBrief.getCreater() != null ? stepBrief.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(stepBrief.getCreateTime(), "yyyy-MM-dd"));
            rMap.put("routeType", stepBrief.getRouteType()==2?"条件路由":"一般路由");
            if(stepBrief.getRouteType()==2){
                String nextStepNo = "";
                List<StepCon> stepConList = stepBrief.getStepConList();
                if(stepConList != null){
                    for(StepCon stepCon:stepConList){
                        if(stepCon.getStepBrief() != null && stepCon.getState().name().equals("Enable")){
                            nextStepNo += stepCon.getStepNo()+",";
                        }
                    }
                }
                if(StringUtils.isNotEmpty(nextStepNo)){
                    nextStepNo = nextStepNo.substring(0, nextStepNo.length()-1);
                }
                rMap.put("nextStepNo",nextStepNo);
            }else{
                rMap.put("nextStepNo",stepBrief.getNextStepNo());
            }
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }





}
